package gui.typeEditors;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JTextField;

import owg.util.Calc;
import owg.util.euclidian.V3D;


public class V3DEditorField extends TypeEditor<V3D> implements ActionListener, FocusListener
	{
	static final long serialVersionUID = 2704835030524222886L;
	
	static final int DEFAULT_COLUMNS = 9;
	
	JTextField field;
	V3D value;
	boolean ignoreEvents = false;
	Color origcolor;
	
	double displayValueMultiplier;
	
	public V3DEditorField(V3D initialValue, int columns, boolean permitGrowing)
		{
		super();
		if(!permitGrowing)
			setLayout(new FlowLayout(FlowLayout.CENTER,0,0));
		
		
		field = new JTextField();
		origcolor = field.getBackground();
		field.setColumns(columns);
		setValue(initialValue, false);
		add(field);
		field.addActionListener(this);
		field.addFocusListener(this);
		}

	protected void setValue(V3D val, boolean fire)
		{
		V3D pVal = value;
		value = val;
		ignoreEvents = true;
		int ppos = field.getCaretPosition();
		field.setText(String.valueOf(val));
		field.setCaretPosition((int)Calc.limit(ppos, 0, field.getText().length()));
		ignoreEvents = false;
		if(fire && !pVal.equals(value))
			{
			fireActionEvents();
			flash(Color.GREEN);
			}
		}

	@Override
	public void focusGained(FocusEvent e)
		{
		
		}

	@Override
	public void focusLost(FocusEvent e)
		{
		if(!ignoreEvents)
			parseValue();
		}

	@Override
	public void actionPerformed(ActionEvent e)
		{
		if(!ignoreEvents)
			parseValue();
		}

	private void parseValue()
		{
		try {
			setValue(V3D.parseV3D(field.getText()), true);
			}
		catch(IllegalArgumentException e)
			{
			flash(Color.RED);
			setValue(value, false);
			}
		}

	synchronized void color(Color color)
		{
		field.setBackground(color);
		}

	private void flash(Color color)
		{
		color(color);
		flashThread(new Runnable(){public void run(){color(origcolor);}}, 33);
		}

	@Override
	public void setToolTipTextToSubComponents(String text)
		{
		field.setToolTipText(text);
		}

	@Override
	public void setSubComponentsEnabled(boolean en)
		{
		field.setEnabled(en);
		}

	@Override
	public V3D getValue()
		{
		return value;
		}

	@Override
	public void setValue(V3D val)
		{
		setValue(val, false);
		}
	}
